package com.it.product.receiver;

import com.it.product.service.IProductService;
import com.rabbitmq.client.Channel;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.rabbit.constants.MqConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;


/**
 * projectName: spzx-parent
 *
 * @author: 王宝贵
 * time: 2024/10/17 21:20 周四
 * description: rabbit消费者 当生产者调用的时候 消费者必须接受消息 目的解库存
 */
@Slf4j
@Component
public class ProductReceiver {

    @Autowired
    private IProductService productService;

    //解锁
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_UNLOCK,durable = "true"),
            key = {MqConst.ROUTING_UNLOCK}
    ))
    public void unlock (String orderNo, Message message, Channel channel) throws IOException {
        //业务处理
        if(StringUtils.isNotEmpty(orderNo)){
            log.info("商品服务 监听解锁库存消息：{}",orderNo);
            //解锁库存
            productService.unlock(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    //减库存
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PRODUCT,durable = "true"),
            value = @Queue(value = MqConst.QUEUE_MINUS,durable = "true"),
            key = {MqConst.ROUTING_MINUS}
    ))
    public void minus (String orderNo, Message message, Channel channel) throws IOException {
        //业务处理
        if(StringUtils.isNotEmpty(orderNo)){
            log.info("商品服务 监听减库存消息：{}",orderNo);
            //减库存
            productService.minus(orderNo);
        }

        //手动应答
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

}